/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.scene.controller;

import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.common.web.Util;
import com.koron.hiddendanger.uitls.BusinessCode;
import com.koron.scene.domain.*;
import com.koron.scene.service.api.OperationActivityService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.ADOConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

/**
 * 作业活动管理
 *
 * @author lwl
 * @since 2023/4/10
 */
@Api(tags = "operationActivity", description = "作业活动接口")
@RestController
@RequestMapping("/operationActivity")
public class OperationActivityController {

    private final static Logger logger = LoggerFactory.getLogger(OperationActivityController.class);
    @Resource
    OperationActivityService operationActivityService;

    @Autowired
    private Util util;

    @ApiOperation("作业活动列表接口")
    @PostMapping("/list.htm")
    public MessageBean list(@StaffAttribute("_user") @ApiIgnore StaffBean user, OperationActivityQuery query) {
        if (null == user) {
            return MessageBean.create(BusinessCode.NOT_LONGIN.getCode(), BusinessCode.NOT_LONGIN.getDescription(), null);
        }
        return ADOConnection.runTask(operationActivityService, "list", MessageBean.class, query);
    }

    @ApiOperation("新增作业活动接口")
    @PostMapping("/add.htm")
    public MessageBean add(@StaffAttribute("_user") @ApiIgnore StaffBean user, OperationActivity bean) {
        if (null == user) {
            return MessageBean.create(BusinessCode.NOT_LONGIN.getCode(), BusinessCode.NOT_LONGIN.getDescription(), null);
        }
        return ADOConnection.runTask(operationActivityService, "add", MessageBean.class, bean, user);
    }

    @ApiOperation("更新作业活动接口")
    @PostMapping("/update.htm")
    public MessageBean update(@StaffAttribute("_user") @ApiIgnore StaffBean user, OperationActivity bean) {
        if (null == user) {
            return MessageBean.create(BusinessCode.NOT_LONGIN.getCode(), BusinessCode.NOT_LONGIN.getDescription(), null);
        }
        return ADOConnection.runTask(operationActivityService, "update", MessageBean.class, bean, user);
    }

    @ApiOperation("删除作业活动接口")
    @GetMapping("/delete.htm")
    public MessageBean delete(@StaffAttribute("_user") @ApiIgnore StaffBean user, String id) {
        if (null == user) {
            return MessageBean.create(BusinessCode.NOT_LONGIN.getCode(), BusinessCode.NOT_LONGIN.getDescription(), null);
        }
        return ADOConnection.runTask(operationActivityService, "delete", MessageBean.class, id);
    }

    @ApiOperation("作业活动详情接口")
    @GetMapping("/detail.htm")
    public MessageBean detail(@StaffAttribute("_user") @ApiIgnore StaffBean user, String id) {
        return ADOConnection.runTask(operationActivityService, "detail", MessageBean.class, id);
    }

    @ApiOperation("作业活动涉及工作票列表")
    @PostMapping("/listOperationTicket.htm")
    public MessageBean listOperationTicket(@StaffAttribute("_user") @ApiIgnore StaffBean user, OperationTicketQuery query) {
        return ADOConnection.runTask(operationActivityService, "listOperationTicket", MessageBean.class, query);
    }

    @ApiOperation("作业活动涉及工作票详情")
    @GetMapping("/queryOperationTicketById.htm")
    public MessageBean queryOperationTicketById(@StaffAttribute("_user") @ApiIgnore StaffBean user, String id) {
        return ADOConnection.runTask(operationActivityService, "queryOperationTicketById", MessageBean.class, id);
    }

    @ApiOperation("保存作业票")
    @PostMapping("/saveOperationTicket.htm")
    public MessageBean saveOperationTicket(@StaffAttribute("_user") @ApiIgnore StaffBean user, OperationTicket bean, HttpServletRequest request) {
        if (null == user) {
            return MessageBean.create(BusinessCode.NOT_LONGIN.getCode(), BusinessCode.NOT_LONGIN.getDescription(), null);
        }
        return ADOConnection.runTask(operationActivityService, "saveOperationTicket", MessageBean.class, request, bean, user);
    }

    @ApiOperation("导出作业票")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "id", value = "作业票id", required = true, dataType = "String", paramType = "query")
    )
    @GetMapping("/exportOperationTicket.htm")
    public void exportOperationTicket(@StaffAttribute("_user") @ApiIgnore StaffBean user, HttpServletResponse response, String id) throws IOException {
        try (OutputStream os = response.getOutputStream()) {
            if (null == user) {
                return ;
            }
            MessageBean<OperationTicket> msg = ADOConnection.runTask(sessionFactory -> operationActivityService.queryOperationTicketById(sessionFactory, id), MessageBean.class);
            OperationTicket bean = msg.getData();
            String operationCode = bean.getOperationCode();
            String operationTicketTypeName = bean.getOperationTicketTypeName();
            String fileName = operationCode+operationTicketTypeName+".pdf";
            response.setContentType("application/pdf");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
            ADOConnection.runTask(factory -> operationActivityService.exportOperationTicket(factory, os, id), Void.class);
            os.flush();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
    }

    @ApiOperation("二维码填报作业票")
    @PostMapping("/saveOperationTicketByQrCode.htm")
    public MessageBean saveOperationTicketByQrCode(@StaffAttribute("_user") @ApiIgnore StaffBean user, OperationTicket bean, HttpServletRequest request, String approver) {
        if (StringUtils.isEmpty(approver)) {
            return MessageBean.create(BusinessCode.FAILURE.getCode(), "二维码已失效", null);
        }
        // 将生成二维码的人作为当前用户
        String userid = String.join("", Arrays.asList(approver.split(",")));
        List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(userid, 2).getData();
        if (null != staffBeanList && staffBeanList.size() > 0) {
            user = staffBeanList.get(0);
        } else {
            return MessageBean.create(BusinessCode.FAILURE.getCode(), "二维码已失效", null);
        }
        return ADOConnection.runTask(operationActivityService, "saveOperationTicketByQrCode", MessageBean.class, request, bean, user, approver);
    }

    @ApiOperation("删除作业票")
    @GetMapping("/deleteOperationTicket.htm")
    public MessageBean deleteOperationTicket(@StaffAttribute("_user") @ApiIgnore StaffBean user, String id) {
        if (null == user) {
            return MessageBean.create(BusinessCode.NOT_LONGIN.getCode(), BusinessCode.NOT_LONGIN.getDescription(), null);
        }
        return ADOConnection.runTask(operationActivityService, "deleteOperationTicket", MessageBean.class, id);
    }

    @ApiOperation("确认作业票完工")
    @PostMapping("/confirm.htm")
    public MessageBean confirm(@StaffAttribute("_user") @ApiIgnore StaffBean user, OperationTicket ticket) {
        if (null == user) {
            return MessageBean.create(BusinessCode.NOT_LONGIN.getCode(), BusinessCode.NOT_LONGIN.getDescription(), null);
        }
        return ADOConnection.runTask(operationActivityService, "confirm", MessageBean.class, ticket);
    }

    @ApiOperation("新增气体分析")
    @PostMapping("/gasAnalysis.htm")
    public MessageBean gasAnalysis(@StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestBody GasAnalysis bean) {
        if (null == user) {
            return MessageBean.create(BusinessCode.NOT_LONGIN.getCode(), BusinessCode.NOT_LONGIN.getDescription(), null);
        }
        return ADOConnection.runTask(operationActivityService, "gasAnalysis", MessageBean.class, bean);
    }

    @ApiOperation("流程中的业务数据")
    @ApiImplicitParam(name = "ids", value = "流程关联的业务ids", required = true, paramType = "query", dataType = "String")
    @RequestMapping(value = "/getProcessData.htm", method = {RequestMethod.GET})
    public MessageBean<?> getProcessData(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String ids) {
        if (null == user) {
            return MessageBean.create(BusinessCode.NOT_LONGIN.getCode(), BusinessCode.NOT_LONGIN.getDescription(), Integer.class);
        }
        return operationActivityService.getProcessData(ids);
    }

    @ApiOperation("流程中作业活动-作业票签名保存接口")
    @PostMapping("/flowSignSave.htm")
    public MessageBean flowSignSave(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                                    @RequestParam(required = true) String id, MultipartFile[] files) {
        if (null == user) {
            return MessageBean.create(BusinessCode.NOT_LONGIN.getCode(), BusinessCode.NOT_LONGIN.getDescription(), Integer.class);
        }
        return ADOConnection.runTask(factory -> operationActivityService.flowSignSave(factory, user, id, files), MessageBean.class);
    }

}
